package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.mapper.DtsRoleMapper;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.PermsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lixu
 */
@Service
public class PermsServiceImpl implements PermsService {
    @Autowired
    private DtsPermissionMapper dtsPermissionMapper;
    @Autowired
    private DtsRoleMapper dtsRoleMapper;

    /**
     * select permission from dts_permission where role_id in
     * @param roleIds
     * @return
     */
    @Override
    public Set<String> findPermsByRoleIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> lambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(DtsPermission::getPermission)
                .in(DtsPermission::getRoleId,roleIds)
                .eq(DtsPermission::getDeleted,false);//不删除
        List<DtsPermission> dtsPermissionList = dtsPermissionMapper.selectList(lambdaQueryWrapper);
        return dtsPermissionList.stream().map(DtsPermission::getPermission).collect(Collectors.toSet());
    }

    /**
     * 授权操作
     * @param roleId
     * @param permissionList
     */
    @Override
    public void updatePermListByRoleId(Integer roleId, List<String> permissionList) {


        DtsRole dtsRole = dtsRoleMapper.selectById(roleId);
        if("超级管理员".equals(dtsRole.getName())){
            //1:是超级管理员
            //不可以修改  永久是*

        }else{
            //2:不是超级
            //2.1:删除原来的权限
            dtsPermissionMapper.delete(new QueryWrapper<DtsPermission>()
                    .eq("role_id",roleId));
            //2.2 添加现在权限
            if(!CollectionUtils.isEmpty(permissionList)){
                permissionList.forEach(permission -> {
                    DtsPermission dtsPermission = new DtsPermission();
                    dtsPermission.setRoleId(roleId);
                    dtsPermission.setPermission(permission);
                    dtsPermission.setDeleted(false);
                    dtsPermission.setAddTime(new Date());
                    dtsPermission.setUpdateTime(new Date());
                    dtsPermissionMapper.insert(dtsPermission);
                });
            }
        }
    }

/*    @Override
    public Set<String> findPermsListByRoleId(Integer roleId) {
        return dtsPermissionMapper.selectList(new QueryWrapper<DtsPermission>()
                .eq("role_id",roleId));
    }*/
}
